package com.authine.cloudpivot.web.Utils;


import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.CorpMessageCorpconversationAsyncsendRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.CorpMessageCorpconversationAsyncsendResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 对接钉钉的工具类
 * @author chenjq
 * @date 2019/6/14
 */
@Slf4j
public class DingDingUtil {

    /**
     * 企业Id
     */
    //private static String CORPID = "dingmnozoqcmpnzxixuz";


    /**
     * 企业Id
     */
    private static String CORPID = "dingd64a493b4d6a591b35c2f4657eb6378f";

    /**
     * 企业应用的凭证密钥
     */
    //private static String CORPSECRET = "XZV46pcdJ2a_OHypMSpFC3eWEpjdmc4ncU_OO1nXimZ3YIaTed95YswEoHpgFtz_";
    /**
     * 企业应用的凭证密钥
     */
    private static String CORPSECRET = "g7wRF8BqZlOOm4pDlGSCpxRx6da-mcCfQGZfpZe2GhaU6vaMGHJfTIdvWr_OSuMi";



    /**
     * 自动分配微应用的ID
     */
    //public static Long AGENTID = 268740166L;

    /**
     * 自动分配微应用的ID
     */
    public static Long AGENTID = 719166558L;

    public static String getToken () {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(CORPID);
        request.setAppsecret(CORPSECRET);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response.getAccessToken();
    }

    /**
     * 发送钉钉工作通知消息
     * @param userIdList 通知用户列表
     * @param msgContent 消息文本
     * @param accessToken token
     * @return
     */
    public static JSONObject sendDDWorkMessage (String userIdList, String msgContent, String accessToken) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(userIdList);
        request.setAgentId(AGENTID);
        request.setToAllUser(false);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
        msg.getText().setContent(msgContent);
        request.setMsg(msg);
        try {
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,accessToken);
            JSONObject jsonObject = JSONObject.fromObject(response);
            log.info("send message to dingding response:{}",jsonObject.toString());
        } catch (ApiException e) {
            log.error("error : {}", e.getMessage());
        }
        return null;
    }

    /**
     * 发送消息
     * @param agentId 微应用的ID
     * @param userId 接收者的用户userid列表
     * @param  msgcontent 消息内容
     */
    public static JSONObject sendDDMessage(Long agentId, String userId, String msgcontent, String token) {
        DingTalkClient client = new DefaultDingTalkClient("https://eco.taobao.com/router/rest");
        CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest();
        // 消息类型
        req.setMsgtype("oa");
        req.setAgentId(agentId);
        req.setUseridList(userId);
        // 是否发送给企业全部用户
        req.setToAllUser(false);
        req.setMsgcontentString(msgcontent);
        try {
            CorpMessageCorpconversationAsyncsendResponse rsp = client.execute(req, token);
            JSONObject json = JSONObject.fromObject(rsp.getResult());
            if (json != null) {
                return json;
            }
        } catch (ApiException e) {

        }
        return null;
    }

    public static String sendHttpPost(String url, String body) throws Exception {
        String result = null;
        HttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder();
        try {

            HttpPost post = new HttpPost(url);
            //设置请求头
            post.setHeader("Content-Type", "application/json");
            //设置请求体
            post.setEntity(new StringEntity(body));
            //获取返回信息
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity = new BufferedHttpEntity(entity);

                InputStream in = entity.getContent();
                byte[] read = new byte[1024];
                byte[] all = new byte[0];
                int num;
                while ((num = in.read(read)) > 0) {
                    byte[] temp = new byte[all.length + num];
                    System.arraycopy(all, 0, temp, 0, all.length);
                    System.arraycopy(read, 0, temp, all.length, num);
                    all = temp;
                }
                result = new String(all,"UTF-8");
                if (null != in) {
                    in.close();
                }
            }
            return result;
        } catch (Exception e) {
            System.out.println("接口请求失败"+e.getStackTrace());
        }
        return result;
    }

    public static String doPost(String url, JSONObject jsonObject, String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            StringEntity entity = new StringEntity(jsonObject.toString(),charset);
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

}
